# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
import xmltodict
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now, utc_to_local

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://gate.iceuptrade.com/cooperate/gateway.cgi'

APP_CONF = {
    '2018012521010186': {
        'API_KEY': '225f55fd46da6ca51ffa22c868227e13',
        'gateway': 'http://gate.iceuptrade.com/cooperate/gateway.cgi'
    },
    '2018041111010212': {  # loki 支付方式和单笔限额：qq，（0---1000）。快捷0---10000.支付宝0---3000
        'API_KEY': '4faa218c160b4c5a1d8c35b43bda521d',
        'gateway': 'http://gate.yofuto.com/cooperate/gateway.cgi'
    },
    '2018041911010221': {
    # dwc 支付方式，费率，单笔限额：qqwap,1.7%(0---5000).d0结算。京东1.6%（0---1w)d0结算。快捷1.5%（0--1w）d0结算。支付宝3%（0---1000）t1结算
        'API_KEY': 'e457e39b4dfef73b0b03446147391ce9',
        'gateway': 'http://gate.xxxxpay.com/cooperate/gateway.cgi'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def generate_sign(parameter, key):
    s = ''
    for k in parameter.keys():
        s += '%s=%s&' % (k, parameter[k])
    s = s[0:len(s) - 1]
    s += key
    _LOGGER.info("tianjipay sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_notify_sign(d, key):
    sss = 'service={}&merId={}&tradeNo={}&tradeDate={}&opeNo={}&opeDate={}&amount={}&status={}&extra={}&payTime={}'.format(
        d['service'], d['merId'], d['tradeNo'], d['tradeDate'], d['opeNo'], d['opeDate'], d['amount'], d['status'],
        d['extra'], d['payTime']
    )
    s = sss + key
    _LOGGER.info("tianjipay notify sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("tianjipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 1;支付宝钱包 2;微信钱包 3; QQ钱包 5;京东钱包H5
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '2'
    elif service == 'alipay':
        payType = '1'
    elif service == 'qq':
        payType = '3'
    else:
        payType = '5'
    return payType


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    if service == 'quick':
        return create_bank_charge(pay, pay_amount, info)
    parameter_dict = OrderedDict((
        ('service', 'TRADE.H5PAY'),
        ('version', '1.0.0.0'),
        ('merId', app_id),
        ('typeId', _get_pay_type(service)),
        ('tradeNo', str(pay.id)),
        ('tradeDate', local_now().strftime('%Y%m%d')),
        ('amount', str(pay_amount)),
        ('notifyUrl', '{}/pay/api/{}/tianjipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('summary', 'charge'),
        ('clientIp', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("tianjipay create  data: %s", parameter_dict)
    html = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def create_bank_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('service', 'TRADE.B2C'),
        ('version', '1.0.0.0'),
        ('merId', app_id),
        ('tradeNo', str(pay.id)),
        ('tradeDate', local_now().strftime('%Y%m%d')),
        ('amount', str(pay_amount)),
        ('notifyUrl', '{}/pay/api/{}/tianjipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('summary', 'charge'),
        ('clientIp', _get_device_ip(info)),
        ('bankId', 'KJZF'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("tianjipay create  data: %s", parameter_dict)
    html = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("tianjipay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['tradeNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('tianjipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['opeNo']
    total_fee = float(data['amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('tianjipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('service', 'TRADE.QUERY'),
        ('version', '1.0.0.0'),
        ('merId', app_id),
        ('tradeNo', str(pay_id)),
        ('tradeDate', utc_to_local(pay_order.updated_at).strftime('%Y%m%d')),
        ('amount', '%.2f' % pay_order.total_fee),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('tianjipay query rsp:%s', response.text)
    if response.status_code == 200:
        data = xmltodict.parse(response.text)['message']['detail']
        trade_status = str(data['status'])
        trade_no = data['opeNo']
        total_fee = float(pay_order.total_fee)

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '1':
            _LOGGER.info('tianjipay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('tianjipay data error, status_code: %s', response.status_code)
